package com.itcast.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.admin.domain.CheckupGroup;
import com.itcast.admin.domain.CheckupItem;
import com.itcast.admin.domain.Setmeal;
import com.itcast.admin.domain.request.CreateGroupReqDTO;
import com.itcast.admin.domain.request.GroupPageReqDTO;
import com.itcast.admin.domain.response.CheckDisableResDTO;
import com.itcast.admin.domain.response.GroupListResDTO;
import com.itcast.admin.domain.response.GroupPageResDTO;
import com.itcast.admin.mapper.CheckupGroupMapper;
import com.itcast.admin.mapper.CheckupItemMapper;
import com.itcast.admin.mapper.SetmealMapper;
import com.itcast.admin.service.ICheckupGroupService;
import com.itcast.admin.service.ICheckupItemService;
import com.itcast.admin.service.ISetmealService;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 体检组 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-04
 */
@Service
public class CheckupGroupServiceImpl extends ServiceImpl<CheckupGroupMapper, CheckupGroup> implements ICheckupGroupService {


    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private ISetmealService setmealService;

    @Autowired
    private CheckupGroupMapper checkupGroupMapper;

    @Autowired
    private CheckupItemMapper checkupItemMapper;

    @Autowired
    private ICheckupItemService iCheckupItemService;
    /**
     * 分页查询体检组
     *
     * @param groupPageReqDTO
     * @return
     */
    @Override
    public PageResult<GroupPageResDTO> pageQuery(GroupPageReqDTO groupPageReqDTO) {
        return PageHelperUtils.selectPage(groupPageReqDTO,()-> baseMapper.groupPage(groupPageReqDTO));
    }

    /**
     * 新增体检组
     *
     * @param createGroupReqDTO
     */
    @Override
    public void insert( CreateGroupReqDTO createGroupReqDTO) {
        CheckupGroup checkupGroup = BeanUtils.copyBean(createGroupReqDTO, CheckupGroup.class);
        //查询新增的体检组是否存在
        if (lambdaQuery().eq(CheckupGroup::getGroupName, checkupGroup.getGroupName()).one() != null){
            throw new BadRequestException("该体检组已存在");
        }
        save(checkupGroup);
    }

    /**
     * 根据id查询体检组
     *
     * @param id
     * @return
     */
    @Override
    public CheckupGroup getCheckGroupById(Integer id) {
        CheckupGroup checkupGroup = lambdaQuery().eq(CheckupGroup::getId, id).one();
        if (checkupGroup == null){
            throw new BadRequestException("查询失败");
        }
        return checkupGroup;
    }

    /**
     * 根据id修改体检组
     *
     * @param id
     * @param createGroupReqDTO
     */
    @Override
    public void updateCheckGroupById(Integer id, CreateGroupReqDTO createGroupReqDTO) {
        //修改体检组,判断体检组名称是否重复
        CheckupGroup checkupGroup = lambdaQuery().eq(CheckupGroup::getGroupName, createGroupReqDTO.getGroupName())
                .ne(CheckupGroup::getId, id).one();
        if (checkupGroup != null){
            throw new BadRequestException("该体检组已存在");
        }
        boolean update = lambdaUpdate().set(CheckupGroup::getGroupName, createGroupReqDTO.getGroupName())
                .set(CheckupGroup::getGroupSortNum, createGroupReqDTO.getGroupSortNum())
                .set(CheckupGroup::getGroupDescription, createGroupReqDTO.getGroupDescription())
                .eq(CheckupGroup::getId, id)
                .update();
        if (!update){
            throw new BadRequestException("修改失败");
        }
    }

    /**
     * 根据id启用检查组
     *
     * @param id
     */
    @Override
    public void enableCheckGroupById(Integer id) {
        boolean update = lambdaUpdate().set(CheckupGroup::getGroupStatus, 1)
                .eq(CheckupGroup::getId, id)
                .update();
        if (!update){
            throw new BadRequestException("启用失败");
        }
    }

    /**
     * 根据id删除检查组
     *
     * @param id
     */
    @Override
    public void deleteCheckGroupById(Integer id) {
        //查询检查组
        CheckupGroup checkupGroup = getCheckGroupById(id);
        if (!(checkupGroup.getGroupStatus() ==0)){
            throw new BadRequestException("状态有误,不可删除");
        }
        boolean removeById = removeById(id);
        if (!removeById){
            throw new BadRequestException("删除失败");
        }
    }

    /**
     * 查询下拉列表
     *
     * @param groupStatus
     */
    @Override
    public List<GroupListResDTO> listForFilter(Integer groupStatus) {
        List<CheckupGroup> list = lambdaQuery().eq(CheckupGroup::getGroupStatus, groupStatus).list();
        if (list.isEmpty()){
            return new ArrayList<>();
        }
        return BeanUtils.copyList(list, GroupListResDTO.class);
    }

    /**
     * 校验检查组是否可以禁用
     *
     * @param checkGroupId
     * @return
     */
    @Override
    public CheckDisableResDTO checkDisableById(Integer checkGroupId) {
        List<String> setmealNames = setmealMapper.checkDisableById(checkGroupId);
        CheckDisableResDTO checkDisableResDTO = new CheckDisableResDTO();
        if (ObjectUtils.isNotNull(setmealNames) && setmealNames.size() > 0){
            //有关联套餐,不能禁用
            checkDisableResDTO.setCanDisable(false);
            checkDisableResDTO.setSetmealNames(setmealNames);
            return checkDisableResDTO;
        }
        checkDisableResDTO.setCanDisable(true);
        checkDisableResDTO.setSetmealNames(setmealNames);
        return checkDisableResDTO;
    }

    /**
     * 根据id禁用检查组
     *
     * @param id
     */
    @Override
    public void disableCheckGroupById(Integer id) {

        //检验是否有关联的体检项
        List<CheckupItem> checkupItems = iCheckupItemService.lambdaQuery().eq(CheckupItem::getCheckGroupId, id)
                .eq(CheckupItem::getItemStatus, 1).select().list();
        if (checkupItems != null && checkupItems.size() > 0){
            throw new BadRequestException("该检查组有关联启用体检项,不可禁用");
        }
        //和查询所有关联的套餐id
        List<Integer> ids = checkupGroupMapper.getSetmealIds(id);
        if (ids != null && ids.size() > 0){
            //禁用所有关联的套餐
            setmealMapper.disableSetmeals(ids);
            //删除套餐中关联的体检组和体检项
            checkupGroupMapper.deleteGroupAtSetmeal(id);
            for (Integer setmealId : ids) {
                //查询关联套餐中关联的检查项ids
                List<Integer> itemIds = checkupGroupMapper.getItemIdsBySetmealId(setmealId);
                //查询建议总价
                BigDecimal totalPrice = checkupItemMapper.getTotalPrice(itemIds);
                //更新价格
                setmealService.lambdaUpdate().set(Setmeal::getSetmealCost, totalPrice).eq(Setmeal::getId, setmealId).update();
            }
        }
        //禁用检查组
        boolean update = lambdaUpdate().set(CheckupGroup::getGroupStatus, 2)
                .eq(CheckupGroup::getId, id)
                .update();
        if (!update){
            throw new BadRequestException("禁用失败");
        }
    }
}
